/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package PersistenciaController;

import Persistencia.Barrio;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Persistencia.Localidad;
import Persistencia.Sitio;
import PersistenciaController.exceptions.IllegalOrphanException;
import PersistenciaController.exceptions.NonexistentEntityException;
import PersistenciaController.exceptions.PreexistingEntityException;
import PersistenciaController.exceptions.RollbackFailureException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author BATAQUERO
 */
public class BarrioJpaController implements Serializable {

    public BarrioJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Barrio barrio) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (barrio.getSitioList() == null) {
            barrio.setSitioList(new ArrayList<Sitio>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Localidad idLocalidad = barrio.getIdLocalidad();
            if (idLocalidad != null) {
                idLocalidad = em.getReference(idLocalidad.getClass(), idLocalidad.getIdLocalidad());
                barrio.setIdLocalidad(idLocalidad);
            }
            List<Sitio> attachedSitioList = new ArrayList<Sitio>();
            for (Sitio sitioListSitioToAttach : barrio.getSitioList()) {
                sitioListSitioToAttach = em.getReference(sitioListSitioToAttach.getClass(), sitioListSitioToAttach.getIdSitio());
                attachedSitioList.add(sitioListSitioToAttach);
            }
            barrio.setSitioList(attachedSitioList);
            em.persist(barrio);
            if (idLocalidad != null) {
                idLocalidad.getBarrioList().add(barrio);
                idLocalidad = em.merge(idLocalidad);
            }
            for (Sitio sitioListSitio : barrio.getSitioList()) {
                Barrio oldIdBarrioOfSitioListSitio = sitioListSitio.getIdBarrio();
                sitioListSitio.setIdBarrio(barrio);
                sitioListSitio = em.merge(sitioListSitio);
                if (oldIdBarrioOfSitioListSitio != null) {
                    oldIdBarrioOfSitioListSitio.getSitioList().remove(sitioListSitio);
                    oldIdBarrioOfSitioListSitio = em.merge(oldIdBarrioOfSitioListSitio);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findBarrio(barrio.getIdBarrio()) != null) {
                throw new PreexistingEntityException("Barrio " + barrio + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Barrio barrio) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Barrio persistentBarrio = em.find(Barrio.class, barrio.getIdBarrio());
            Localidad idLocalidadOld = persistentBarrio.getIdLocalidad();
            Localidad idLocalidadNew = barrio.getIdLocalidad();
            List<Sitio> sitioListOld = persistentBarrio.getSitioList();
            List<Sitio> sitioListNew = barrio.getSitioList();
            List<String> illegalOrphanMessages = null;
            for (Sitio sitioListOldSitio : sitioListOld) {
                if (!sitioListNew.contains(sitioListOldSitio)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Sitio " + sitioListOldSitio + " since its idBarrio field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idLocalidadNew != null) {
                idLocalidadNew = em.getReference(idLocalidadNew.getClass(), idLocalidadNew.getIdLocalidad());
                barrio.setIdLocalidad(idLocalidadNew);
            }
            List<Sitio> attachedSitioListNew = new ArrayList<Sitio>();
            for (Sitio sitioListNewSitioToAttach : sitioListNew) {
                sitioListNewSitioToAttach = em.getReference(sitioListNewSitioToAttach.getClass(), sitioListNewSitioToAttach.getIdSitio());
                attachedSitioListNew.add(sitioListNewSitioToAttach);
            }
            sitioListNew = attachedSitioListNew;
            barrio.setSitioList(sitioListNew);
            barrio = em.merge(barrio);
            if (idLocalidadOld != null && !idLocalidadOld.equals(idLocalidadNew)) {
                idLocalidadOld.getBarrioList().remove(barrio);
                idLocalidadOld = em.merge(idLocalidadOld);
            }
            if (idLocalidadNew != null && !idLocalidadNew.equals(idLocalidadOld)) {
                idLocalidadNew.getBarrioList().add(barrio);
                idLocalidadNew = em.merge(idLocalidadNew);
            }
            for (Sitio sitioListNewSitio : sitioListNew) {
                if (!sitioListOld.contains(sitioListNewSitio)) {
                    Barrio oldIdBarrioOfSitioListNewSitio = sitioListNewSitio.getIdBarrio();
                    sitioListNewSitio.setIdBarrio(barrio);
                    sitioListNewSitio = em.merge(sitioListNewSitio);
                    if (oldIdBarrioOfSitioListNewSitio != null && !oldIdBarrioOfSitioListNewSitio.equals(barrio)) {
                        oldIdBarrioOfSitioListNewSitio.getSitioList().remove(sitioListNewSitio);
                        oldIdBarrioOfSitioListNewSitio = em.merge(oldIdBarrioOfSitioListNewSitio);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = barrio.getIdBarrio();
                if (findBarrio(id) == null) {
                    throw new NonexistentEntityException("The barrio with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Barrio barrio;
            try {
                barrio = em.getReference(Barrio.class, id);
                barrio.getIdBarrio();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The barrio with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Sitio> sitioListOrphanCheck = barrio.getSitioList();
            for (Sitio sitioListOrphanCheckSitio : sitioListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Barrio (" + barrio + ") cannot be destroyed since the Sitio " + sitioListOrphanCheckSitio + " in its sitioList field has a non-nullable idBarrio field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Localidad idLocalidad = barrio.getIdLocalidad();
            if (idLocalidad != null) {
                idLocalidad.getBarrioList().remove(barrio);
                idLocalidad = em.merge(idLocalidad);
            }
            em.remove(barrio);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Barrio> findBarrioEntities() {
        return findBarrioEntities(true, -1, -1);
    }

    public List<Barrio> findBarrioEntities(int maxResults, int firstResult) {
        return findBarrioEntities(false, maxResults, firstResult);
    }

    private List<Barrio> findBarrioEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Barrio.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Barrio findBarrio(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Barrio.class, id);
        } finally {
            em.close();
        }
    }

    public int getBarrioCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Barrio> rt = cq.from(Barrio.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
